//
//  DiDiTunnelLogStore.m
//  KDExample
//
//  Created by YeQing on 2017/4/7.
//  Copyright © 2017年 naruto. All rights reserved.
//  滴滴 vpn协议组件 - 日志模块
//  日志路径：[/private/var/mobile/Containers/Shared/AppGroup/AA6EE05A-C805-4037-A50A-E6B9D8147F23/...]


#import "DiDiTunnelLogStore.h"
#import <CoreGraphics/CGBase.h>

#define kDiDiTunnelLog_Level                        3//该等级以下的日志不输出
#define kDiDiTunnelLog_GroupName                    @"group.com.naruto.fruit"//group name
#define kDiDiTunnelLog_GroupLogDir                  @"ddpacktunnel"//log  dir  name
#define kDiDiTunnelLog_GroupLogFile                 @"tunel.log"//log name
#define kDiDiTunnelLog_DirMaxSize                   10*1024*1024    //日志文件夹最大size


@interface DiDiTunnelLogStore()

/**
 写文件的队列
 */
@property (nonatomic, strong) dispatch_queue_t              bcLogSerialOperation;

/**
 日志 格式化formater
 */
@property (nonatomic, strong) NSDateFormatter               *logFormater;
/**
 日志文件夹的路径
 */
@property (nonatomic, strong) NSString                      * bcLogDirPath;
/**
 日志文件的路径
 */
@property (nonatomic, strong) NSString                      * bcLogFilePath;
@end

@implementation DiDiTunnelLogStore

#pragma mark - system
+ (instancetype) shareInstance
{
    static dispatch_once_t kDiDiTunnelLogOnceToken;
    static DiDiTunnelLogStore *kkDiDiTunnelLogInstance = nil;
    dispatch_once(&kDiDiTunnelLogOnceToken, ^{
        kkDiDiTunnelLogInstance = [DiDiTunnelLogStore new];
    });
    return kkDiDiTunnelLogInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _bcLogSerialOperation = dispatch_queue_create("com.dispatch.serial.ddpacktunnel", DISPATCH_QUEUE_SERIAL);
        _logFormater = [[NSDateFormatter alloc ] init];
        [_logFormater setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
        [self createLogFile];
    }
    return self;
}



#pragma mark - private

/**
 创建日志文件目录
 */
-(void)createLogFile
{
    NSURL *strLogDirURL =  [[DiDiTunnelLogStore groupPath] URLByAppendingPathComponent:kDiDiTunnelLog_GroupLogDir];
    self.bcLogDirPath = strLogDirURL.path;
    NSURL *strLogFileURL =  [strLogDirURL URLByAppendingPathComponent:kDiDiTunnelLog_GroupLogFile];
    self.bcLogFilePath = strLogFileURL.path;
    //判断日志目录大小是否超出限制
    CGFloat currentLogSize = [self getLogFileSize];
    if(currentLogSize >= kDiDiTunnelLog_DirMaxSize){
        //超出最大限制，先删除日志根目录
#ifdef DEBUG
        NSLog(@"DDPT log is too large: %lfKB",currentLogSize);
#endif
        [[NSFileManager defaultManager] removeItemAtPath:self.bcLogDirPath error:nil];
    }
    
    
    //判断 日志文件夹 是否存在
    BOOL isDirExist = [[NSFileManager defaultManager] fileExistsAtPath:self.bcLogDirPath];
    if(!isDirExist){
        bool createLogDir =[[NSFileManager defaultManager] createDirectoryAtPath:self.bcLogDirPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!createLogDir){
#ifdef DEBUG
            NSLog(@"DDPT create dir error:%@",self.bcLogDirPath);
            self.bcLogFilePath = nil;
#endif
            return;
        }
    }
    //判断 日志文件 是否存在
    BOOL isFileExist = [[NSFileManager defaultManager] fileExistsAtPath:self.bcLogFilePath];
    if(!isFileExist){
        bool createLogFile = [[NSFileManager defaultManager] createFileAtPath:self.bcLogFilePath contents:nil attributes:nil] ;
        if(!createLogFile){
#ifdef DEBUG
            NSLog(@"DDPT create file error:%@",self.bcLogFilePath);
            self.bcLogFilePath = nil;
#endif
            return;
        }
    }
#ifdef DEBUG
    NSLog(@"DDPT init success: %lfKB",currentLogSize);
#endif
}


#pragma mark - 读写日志

/**
 写日志
 
 @param strLog 内容
 */
- (void)writeLog:(NSString *)strLog label:(NSString *)label
{
    //判断日志文件是否ok
    if(self.bcLogFilePath.length<=0){
        return;
    }
    if(!self.bcLogSerialOperation){
        return;
    }
    __weak typeof(self) weakSelf = self;
    dispatch_async(self.bcLogSerialOperation, ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        //创建handle
        NSFileHandle *logFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:strongSelf.bcLogFilePath];
        if(!logFileHandle){
#ifdef DEBUG
            NSLog(@"DDPT handle file error:%@",strongSelf.bcLogFilePath);
#endif
            return;
        }
        NSString *strNewLog = nil;
        if(label.length>0){
            strNewLog = [NSString stringWithFormat:@"[%@] %@:%@\r\n",[strongSelf.logFormater stringFromDate:[NSDate date]],label,strLog];
        }
        else{
            strNewLog = [NSString stringWithFormat:@"[%@] %@\r\n",[strongSelf.logFormater stringFromDate:[NSDate date]],strLog];
        }
        [logFileHandle seekToEndOfFile];
        NSData *strData = [strNewLog dataUsingEncoding:NSUTF8StringEncoding];
        [logFileHandle writeData:strData];
        [logFileHandle closeFile];
    });
}

void DiDiTunnelLogWrite(int level, NSString *label, NSString *format, ...)
{
    NSString *strMsg = @"";
    if(format.length>0){
        va_list args;
        va_start(args, format);
        strMsg = [[NSString alloc] initWithFormat:format arguments:args];
        va_end(args);
    }
    
#ifdef DEBUG
    if(level >= kDiDiTunnelLog_Level){
        NSLog(@"%@", strMsg);
    }
#endif
    [[DiDiTunnelLogStore shareInstance] writeLog:strMsg label:label];
    
}



/**
 计算日志文件夹大小
 
 @return 返回KB
 */
- (CGFloat )getLogFileSize
{
    NSFileManager *manager = [NSFileManager defaultManager];
    return  [[manager attributesOfItemAtPath:self.bcLogFilePath error:nil] fileSize]/(1024.0);//这里返回的单位是KB
}

#pragma mark - 获取group 相关路径
/**
 获取group主app 路径
 
 @return NSURL
 */
+ (NSURL *)groupPath
{
    return [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:kDiDiTunnelLog_GroupName];
}

@end
